﻿#region

using System;
using MediaSage.Lib.Utilities;
using NHibernate;
using NHibernate.Criterion;

#endregion

namespace MediaSage.Lib.Database
{
    /// <summary>
    ///     Used for similar movies/tv shows/etc
    /// </summary>
    public class SimilarItemEntity : DatabaseObject
    {
        #region Constructors

        public SimilarItemEntity()
        {
            ID = Guid.NewGuid();
        }

        #endregion

        public virtual Guid ID { get; set; }

        public virtual string IMDBID { get; set; }

        public virtual int TVDBID { get; set; }

        public virtual int TMDBID { get; set; }

        public virtual string Title { get; set; }

        public virtual ImageEntity Poster { get; set; }

        public override void Save()
        {
            ISession session = DBUtil.GetSession();
            using (session.BeginTransaction())
            {
                SimilarItemEntity simItem = null;
                Disjunction disj = Restrictions.Disjunction();
                disj.Add(Restrictions.Eq("TMDBID", TMDBID));
                disj.Add(Restrictions.Eq("IMDBID", IMDBID));
                disj.Add(Restrictions.Eq("TVDBID", TVDBID));
                simItem = session.CreateCriteria(typeof(SimilarItemEntity)).Add(disj).UniqueResult<SimilarItemEntity>();

                if (simItem != null)
                {
                    ID = simItem.ID;
                    IMDBID = simItem.IMDBID;
                    TVDBID = simItem.TVDBID;
                    TMDBID = simItem.TMDBID;
                }
            }
            base.Save();
        }

        public override void SaveOrUpdate()
        {
            ISession session = DBUtil.GetSession();
            using (session.BeginTransaction())
            {
                SimilarItemEntity simItem = null;
                Disjunction disj = Restrictions.Disjunction();
                disj.Add(Restrictions.Eq("TMDBID", TMDBID));
                disj.Add(Restrictions.Eq("IMDBID", IMDBID));
                disj.Add(Restrictions.Eq("TVDBID", TVDBID));
                simItem = session.CreateCriteria(typeof(SimilarItemEntity)).Add(disj).UniqueResult<SimilarItemEntity>();

                if (simItem != null)
                {
                    ID = simItem.ID;
                    IMDBID = simItem.IMDBID;
                    TVDBID = simItem.TVDBID;
                    TMDBID = simItem.TMDBID;
                }
            }

            base.SaveOrUpdate();
        }
    }
}